﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model.Util;
using Model.WeiXin;
using Services.WeiXinProject;
using Xproject.Util;

namespace WeiXinpProAdmin.Controllers
{
    public class WXUserController : AdminBaseController
    {

        public UserInfoServices m_UserInfoServices;
        public WXUserController(UserInfoServices mUserInfoServices)
        {
            m_UserInfoServices = mUserInfoServices;
        }
        // GET: WXUser
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult WXUserList()
        {
            return View();
        }

        public ActionResult WXUserEdit(string userId)
        {
            WeiXinUser model = null;
            if (!string.IsNullOrEmpty(userId))
            {
                model = m_UserInfoServices.GetById(userId);
            }
            return View(model);
        }

        public JsonResult EditWXUser(FormCollection collection)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string ID = collection["ID"];
           
            HttpRequest request = System.Web.HttpContext.Current.Request;
            HttpFileCollection FileCollect = request.Files;
            UploadFile uf = new UploadFile();
            WeiXinUser user = new WeiXinUser();
            string password = collection["Password"];
            string comfirmPassword = collection["ComfirmPassword"];
            if (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(comfirmPassword))
            {
                if (password != comfirmPassword)
                {
                    jsonData = new { Success = false, Data = "两次密码不一致！" };
                    return Json(jsonData, JsonRequestBehavior.AllowGet);
                }
                user.Password = CommonHelper.MD5(password);
            }
            if (!string.IsNullOrEmpty(ID))
            {
                user = m_UserInfoServices.GetById(ID);
            }
            else {
                user.OpenId = "Robot-" + Guid.NewGuid().ToString().Substring(1,26) ;
                user.NickName = collection["NickName"];
                user.UserID = Guid.NewGuid().ToString();
            }
             
            if (FileCollect.Count > 0) //如果集合的数量大于0 
            {
                string Virbase = @"Upload\Images\UserHeadFace\";
                string DataTimeFolder = DateTime.Now.ToString("yyyyMMdd");
                string localpath = AppDomain.CurrentDomain.BaseDirectory + Virbase;
                string Folder = localpath + DataTimeFolder;
               if(!Directory.Exists(Folder))
               {
                    Directory.CreateDirectory(Folder);
               }
                HttpPostedFile FileSave = FileCollect[0]; //用key获取单个文件对象HttpPostedFile 

                uf.FileName = FileSave.FileName;
                uf.FileExt = Path.GetExtension(FileSave.FileName);
                uf.FileSize = FileSave.ContentLength;
                uf.Site = Site;
                uf.ServiceAddress = CommonHelper.GetAppSettings("Domain");
                string guidName = Guid.NewGuid().ToString() + uf.FileExt;
                uf.Path = ("\\" + Virbase + DataTimeFolder + "\\" + guidName).Replace("\\", "/");
                uf.FileId = Guid.NewGuid().ToString();
                string LocalFullPath = Folder + @"\" + guidName;
                uf.LocalFullPath = LocalFullPath;
                FileSave.SaveAs(LocalFullPath); //将上传的东西保存                                                           
                user.HeadUrl = uf.ServiceAddress + uf.Path;
            }                     
            user.Mobile = collection["Mobile"];
            user.GradeID = int.Parse(collection["GradeID"]);
            if (!string.IsNullOrEmpty(ID))
            {
                success = m_UserInfoServices.EditWeiXinUser(user, uf);
            }
            else
            {
                success = m_UserInfoServices.AddWeiXinUser(user, uf);
            }
            
            result = (success) ? "编辑用户成功！" : "编辑用户失败！";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetWXUserList(int offset,int limit,string nickName,string userCode,string mobile,int state, DateTime? startTime, DateTime? endTime, string order, string ordername)
        {
            var lstRes = new List<WeiXinUser>();
            int total = 0;
            lstRes = m_UserInfoServices.GetWeiXinUserList(Site, offset, limit, nickName, userCode,mobile,state,startTime,endTime,order,ordername, out total);
            return Json(new { total = total, rows = lstRes }, JsonRequestBehavior.AllowGet);
        }
    }
}